<?php

namespace common\models\course;

use Yii;
use common\helpers\StringHelper;
use common\helpers\Url;
use yii\imagine\Image;
use common\helpers\FileHelper;

/**
 * This is the model class for table "{{%course}}".
 *
 * @property int $id
 * @property string $number 课程编号
 * @property string $name 课程标题
 * @property string $cover 课程展示封面
 * @property int $category_id 课程类别ID
 * @property int $begin_time 开课时间
 * @property int $duration 课程时长
 * @property int $enroll_begin_time 报名开始时间
 * @property int $enroll_end_time 报名截止时间
 * @property int $enroll_limit 报名人数限制
 * @property int $school_id 学校ID
 * @property int $classroom_id 教室ID
 * @property string $price 课程费用（元）
 * @property int $age_min 面向年龄下限
 * @property int $age_max 面向年龄上限
 * @property int $teacher_id 发起人教师ID
 * @property int $audit_status 审核状态
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class Course extends \common\base\ActiveRecord {

    const STATUS_ACTIVE = 10;
    const STATUS_DEFAULT = 0;
    //
    const AUDIT_STATUS_ACTIVE = 10;
    const AUDIT_STATUS_DEFAULT = 0;
    const AUDIT_STATUS_REFUSE = -1;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%course}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['number', 'name', 'cover'], 'required'],
            [['category_id', 'begin_time', 'duration', 'enroll_begin_time', 'enroll_end_time', 'enroll_limit', 'school_id', 'classroom_id', 'age_min', 'age_max', 'teacher_id', 'audit_status', 'status', 'created_at', 'updated_at'], 'integer'],
            [['price'], 'number'],
            [['number'], 'string', 'max' => 32],
            [['name'], 'string', 'max' => 100],
            [['cover'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'number' => '课程编号',
            'name' => '课程标题',
            'cover' => '课程展示封面',
            'category_id' => '课程类别ID',
            'begin_time' => '开课时间',
            'duration' => '课程时长',
            'enroll_begin_time' => '报名开始时间',
            'enroll_end_time' => '报名截止时间',
            'enroll_limit' => '报名人数限制',
            'school_id' => '学校ID',
            'classroom_id' => '教室ID',
            'price' => '课程费用（元）',
            'age_min' => '面向年龄下限',
            'age_max' => '面向年龄上限',
            'teacher_id' => '发起人教师ID',
            'audit_status' => '审核状态',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public function getTeacher() {
        return $this->hasOne(\common\models\teacher\Teacher::className(), ['id' => 'teacher_id']);
    }

    public function getSchool() {
        return $this->hasOne(\common\models\school\School::className(), ['id' => 'school_id']);
    }

    public function getClassroom() {
        return $this->hasOne(\common\models\school\Classroom::className(), ['id' => 'classroom_id']);
    }

    public function getThumb() {
        return Url::toRemote($this->cover);
    }

    public function getFinished() {
        return $this->begin_time + $this->duration < time();
    }

    public function getData() {
        return $this->hasOne(CourseData::className(), ['course_id' => 'id']);
    }

    public function getBody() {
        return $this->data ? $this->data->content : '暂无课程描述信息';
    }

    public function getLimit() {
        return $this->enroll_limit ? $this->enroll_limit . '人' : '不限';
    }

    public function getAgeRange() {
        $min = $this->age_min ?: 0;
        $max = $this->age_max ?: 0;
        if ($min || $max) {
            return ($min ? $min . '岁' : '不限') . '-' . ($max ? $max . '岁' : '不限');
        } else {
            return '不限年龄';
        }
    }

    public function getMyEnroll() {
        return $this->hasOne(CourseOrder::className(), ['course_id' => 'id'])->andWhere([
            'user_id' => Yii::$app->user->id,
        ]);
    }

    public function getOrder() {
        return $this->hasOne(CourseOrder::className(), ['course_id' => 'id'])->andWhere([
            'user_id' => Yii::$app->user->id,
        ]);
    }

    public function getOrders() {
        return $this->hasMany(CourseOrder::className(), ['course_id' => 'id']);
    }

    public function getEnrolls() {
        return $this->getOrders()->andWhere([
            'and',
            ['status' => CourseOrder::STATUS_PAID],
            ['>', 'pay_time', 0],
            ['is not', 'out_trade_no', null],
        ])->count();
    }

    public function getPlace() {
        $place = '';
        if ($this->school) {
            $place .= StringHelper::trimBlank($this->school->region . $this->school->address_detail);
        }
        if ($this->classroom) {
            $place .= ' ' . $this->classroom->name;
        }
        return $place;
    }

    public function getHistory() {
        return $this->hasOne(\common\models\user\UserHistory::className(), ['course_id' => 'id']);
    }

    public function canEnroll() {
        Yii::error([
            'name' => 'canEnroll',
            'enrolls' => $this->enrolls,
            'enroll_limit' => $this->enroll_limit,
            'enroll_end_time' => $this->enroll_end_time,
            'current_time' => time(),
            'status' => $this->status,
            'attributes' => $this->attributes
        ]);
        return $this->status == self::STATUS_ACTIVE && $this->enroll_end_time > time() && $this->enrolls < $this->enroll_limit;
    }

    public function getShare() {
        $savepath = Yii::getAlias('@uploads') . '/share/' . $this->cover;
        Yii::error([
            'savepath' => $savepath
        ]);
        if (!file_exists($savepath)) {
            FileHelper::createDirectory(dirname($savepath));
            Image::thumbnail($this->thumb, 50, 50)->save($savepath, ['quality' => 100]);
        }
        return [
            'title' => StringHelper::truncate($this->name, 50),
            'desc' => StringHelper::truncate($this->name, 100),
            'img_url' => Url::toRemote('/share' . $this->cover),
            'link' => Url::share(['/share/view', 'id' => $this->id]),
        ];
    }

}
